/*
 * voltage.c
 *
 *  Created on: 2021年7月12日
 *      Author: 91401
 */
#include "voltage.h"
#include "stdlib.h"
#include "cat1.h"
#include "saveconfig.h"

osMessageQDef(volt_q,10,uint32_t);
osMessageQId volt_q_id;

#define VBUF_LEN 10
uint16_t vbuf[VBUF_LEN];

void StartVoltageTask(void const * argument)
{
	volatile HAL_StatusTypeDef st;
	//校准
    st = HAL_ADCEx_Calibration_Start(&hadc1);

    float a=1,b=0;
    if(config_is_valid())
	{
		a = pconfig->cali.volt_a;
		b = pconfig->cali.volt_b;
		DEBUG_PRINT("load volt cali successed\r\n");
	}
	DEBUG_PRINT("volt cali: a=%.3f, b=%.3f\r\n",a,b);

    //主循环
	while(1)
	{
		//开始传输
		st = HAL_ADC_Start_DMA(&hadc1, vbuf, VBUF_LEN);

		//等待传输完成
		osEvent evt = osSignalWait(SIGNAL_VOLT_CPLT, osWaitForever);
		HAL_ADC_Stop_DMA(&hadc1);
		if(evt.status == osEventSignal)
		{
			//计算均值
			uint32_t volt=0;
			for(int i=0;i<VBUF_LEN;i++)
			{
				volt += vbuf[i]/VBUF_LEN;
			}
			float v = volt*VLSB*a+b;

			//上报电压值
			char *p = malloc(32);
			if(p)
			{
				sprintf(p,"{\\\\22voltage\\\\22:%3.3f}",v);
				osMessagePut(publish_q_id, (uint32_t)p, 0);
			}
		}
		osDelay(10000);
	}
}


